package cn.wsn2018.tools.util;

import cn.wsn2018.tools.common.CommonValue;

import cn.wsn2018.tools.model.MySessionContext;
import org.apache.log4j.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 精简化controller的逻辑，将一些固定的设置操作放到此工具类中
 * 将该类设置成线程安全的单例模式
 */
public class ServletUtil {

    private Logger logger = Logger.getLogger(ServletUtil.class);
    private static ServletUtil instance=null;

    public static final HashMap<String,String> operatorTypeMap=new HashMap<String,String>(){
        {
            put(CommonValue.LOGIN_MODULE,"请求系统登录模块接口");
            put(CommonValue.OPERATOR_MODULE,"请求操作员模块接口");
            put(CommonValue.AUDITOR_MODULE,"请求审计员模块接口");
            put(CommonValue.SYS_AUDITOR_MODULE,"请求系统审计员模块接口");
            put(CommonValue.ADMIN_MODULE,"请求系统管理员模块接口");
        }
    };

    //记录当日登录失败次数
    private volatile static ConcurrentHashMap<String,Integer> resMap=null;

    //获取resMap的单例
    public static ConcurrentHashMap getResMap(){
        if(resMap==null){
            synchronized (ConcurrentHashMap.class){
                if (resMap==null)
                    resMap=new ConcurrentHashMap<String,Integer>();
            }

        }
        return resMap;
    }

    //获取当前账号填写验证码失败的次数
    public static Integer getFailedNum(String username){
        Integer num = (Integer) getResMap().get(username);
        if(num==null){
            //用户第一次登录失败
            num=new Integer(0);
            getResMap().put(username,0);
        }
        return num;
    }

    //更新记录-用户失败次数
    public static void updateFailedNum(String username,Integer num){
        getResMap().put(username,num);
    }

    //记录用户对同一个请求的时间戳
    //存放用户上次请求的时间，如果两次请求时间太短就不处理
    private static ConcurrentHashMap<String, String> userTimeStampMap = new ConcurrentHashMap<>();

    //获取时间戳map的单例
    public static ConcurrentHashMap<String,String> getUserTimeStampMap(){
        if (userTimeStampMap==null){
            synchronized (ConcurrentHashMap.class){
                if (userTimeStampMap==null){
                    userTimeStampMap=new ConcurrentHashMap<String,String>();
                }
            }
        }
        return userTimeStampMap;
    }


    private ServletUtil(){}

    /**
     * 得到单例的接口，确保只有一个实例
     * @return
     */
    public static ServletUtil getInstance(){
        if(instance==null){
            synchronized(ServletUtil.class){
                if(instance==null)
                    instance=new ServletUtil();
            }
        }
        return instance;
    }
    /**
     * 处理HttpResponse的一些设置和返回输出操作
     * @param response
     * @param jsonString 从service返回的json字符串
     * @throws Exception
     */
    public void responseOperating(HttpServletResponse response, String jsonString) throws Exception {
        response.setCharacterEncoding("utf-8");
        response.setHeader("content-type", "text/html; charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Expose-Headers","token");
        response.getWriter().write(jsonString);
    }

    /**
     * 处理HttpRequest的字符集设置操作
     * @param request
     * @throws Exception
     */
    public void requestOperating(HttpServletRequest request)throws Exception{
        request.setCharacterEncoding("utf-8");
    }

    /**
     * @Description:获取ip地址
     * @Param: [request]
     * @return: java.lang.String
     * @Author: SongDaisong
     * @Date: 12:43
     */
    public static String getClientIp(HttpServletRequest request) {

        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip == null || ip.length() == 0 || ip.indexOf(":") > -1) {
            try {
                ip = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                ip = null;
            }
        }
        return ip;
    }

    /**
     * @Description: 根据token值获取用户名
     * @Param: [request, token]
     * @return: java.lang.String
     * @Author: SongDaisong
     * @Date:  2020/2/24 13:22
     */
    public static String getUserNameByToken(String token) throws Exception {
        MySessionContext myc= MySessionContext.getInstance();
        HttpSession session = myc.getSession(token);
        String username = session.getAttribute("username").toString();
        return username;
    }
}
